package com.edroid.droidhelper.pc.model;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.edroid.droidhelper.pc.apkutils.ApkInfo;
import com.edroid.droidhelper.pc.apkutils.ApkUtil;
import com.edroid.droidhelper.pc.bean.InstallLogBean;
import com.edroid.droidhelper.pc.util.DeviceUtil;
import com.edroid.droidhelper.pc.util.Logger;
import com.edroid.droidhelper.pc.util.TimeUtils;

/**
 * apk安装任务
 * 
 * @author yichou 2015-1-8
 *
 */
public class InstallTask implements IInstallTask, Runnable {
	static final Logger log = Logger.create("ApkInstallTask");
	
	private int total, cur;
	private boolean isRun;
	private List<String> appList;
	private IPhone device;
	private OnProgUpdateListener listener;
	private List<String> installedAppList;
	private Thread taskThread;
	
	
	public InstallTask(IPhone device) {
		this.device = device;
		
		appList = new ArrayList<String>();
		installedAppList = new ArrayList<String>();
		
		String[] ss = new File(AppGlobal.PATH_APPS).list();
		if(ss != null) {
			total = ss.length;
			cur = 1;
			
			for(String s : ss)
				appList.add(s);
		}
	}
	
	@Override
	public void run() {
		while (isRun) {
			if(cur > total) { //完成
				cur = total;
				if(listener != null) listener.onProgUpdate(this, total, cur, "安装完成！");
				break;
			}
			
			if(!device.isAvailable()) { //不在线了
				if(listener != null) listener.onProgUpdate(this, total, cur, "设备连接失败！");
				isRun = false;
				return;
			}
			
			String name = appList.get(cur - 1);
			try {
				if(listener != null) listener.onProgUpdate(this, total, cur, "安装：" + name);
				log.i("开始安装：" + name);
				long t0 = System.currentTimeMillis();
				
				String apkPath = AppGlobal.PATH_APPS + File.separator + name;
				ApkInfo apkInfo = ApkUtil.getApkInfo(apkPath);
				
				device.installApk(apkPath);
				installedAppList.add(apkInfo.getPackageName());

				if(listener != null) listener.onProgUpdate(this, total, cur, "->成功 " + (System.currentTimeMillis() - t0) + "ms");
			} catch (Exception e1) {
				e1.printStackTrace();
				if(listener != null) listener.onProgUpdate(this, total, cur, "->失败");
			}
			
			cur++;

			try {
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}

		//		if()
		
		//下一步
		packLog();
		
		isRun = false;
	}
	
	private void packLog() {
		if(installedAppList.size() == 0) {
			log.w("no app installed!");
			return;
		}
		log.i("installed app count=" + installedAppList.size());
		
		InstallLogBean bean = new InstallLogBean();
		bean.userId = AppGlobal.userid;
		bean.imei = device.getImei();
		bean.model = device.getModel();
		bean.manufacturer = device.getManufacturer();
		bean.osver = device.getOsVer();
		bean.hostname = device.getHostName();
		
		bean.toolType = "pc";
		bean.toolName = DeviceUtil.getDeviceName();
		bean.toolMac = DeviceUtil.getMac();
		bean.toolIp = DeviceUtil.getIp();
		bean.toolOs = DeviceUtil.getOsName();
		
		bean.appCount = String.valueOf(installedAppList.size());
		
		StringBuilder sb = new StringBuilder(256);
		for(String s : installedAppList) {
			sb.append(s).append(',');
		}
		bean.appList = sb.substring(0, sb.length()-1);
		
		bean.time = TimeUtils.getDateTimeNow();
		bean.timeMills = String.valueOf(TimeUtils.currentTimeMillis());
		
		InstallLogManager.getInstance().add(bean);
		log.i("pack log suc!");
	}

	@Override
	public int getProgTotal() {
		return total;
	}

	@Override
	public int getProgCur() {
		return cur;
	}

	@Override
	public String getCurLabel() {
		return null;
	}

	@Override
	public synchronized void start() {
		if(total <= 0) {
			log.e("没有应用");
			return;
		}

		if(!isRun) {
			isRun = true;
			taskThread = new Thread(this, "taskThread");
			taskThread.start();

			log.i("启动装机线程");
		}
	}
	
	@Override
	public void stop(boolean waitForFinish) {
		if(!isRun)
			packLog();
		else {
			isRun = false;

			if(waitForFinish) {
				try {
					taskThread.join();
				} catch (Exception e) {
				}
			}
		}
	}

	@Override
	public void setOnProgUpdateListener(OnProgUpdateListener listener) {
		this.listener = listener;
		
		listener.onProgUpdate(this, total, cur, null);
	}
}
